import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeepPartial, In, Repository } from 'typeorm';
import { User } from './modules/user.entity';
import { getUserDto } from './dto/get-user.dto';

@Injectable()
export class UserService {
    constructor(@InjectRepository(User) private UserRepository: Repository<User>) {}
    // 新增用户
    async create(entity: DeepPartial<User>): Promise<any> {
        // if (entity.roles instanceof Array && typeof entity.roles[0] === 'number') {
        //     // 查询所有的用户角色
        //     entity.roles = await this.rolesRepository.find({
        //         while: {
        //             id: In(entity.roles)
        //         }
        //     })
        // }
        const userTmp = this.UserRepository.create(entity);
        const oldres = await this.UserRepository.save(userTmp);
        // const res = await this.UserRepository.insert(entity);
        return oldres;
    }

    // 查询用户信息
    async find(username: string): Promise<User> {
        const res = await this.UserRepository.findOne({
            where: {
                username,
            },
        });
        return res;
    }
    // 查询用户信息
    async finduser(username: string): Promise<User> {
        const res = await this.UserRepository.findOne({
        where: {
            username,
        },
        });
        return res;
    }

    // 查询所有用户信息
    async findAll(query: getUserDto): Promise<any> {
        const { limit, page, username } = query;
        const take = limit || 10;
        const skip = ((page || 1) - 1) * take;
        
        // 使用 createQueryBuilder 来构建查询
        const usersCount = await this.UserRepository.createQueryBuilder("user")
            .leftJoinAndSelect("user.profile", "profile") // 假设你想要统计的总数中包括 profile 关联
            .leftJoinAndSelect("user.roles", "roles") // 同上，如果 roles 是你要关联的
            .where("user.username LIKE :username", { username: `%${username}%` }) // 根据 username 查询
            .getCount(); // 使用 getCount() 获取总数

        // 获取总记录数
        const users = await this.UserRepository.find({
            relations: ['profile', 'roles'],
            where: {
                username
            },
            take,
            skip,
        })
        return {
            code: 200,
            data: users,
            total: usersCount,
            msg: '查询成功！'
        };
    }

    // 更新用户信息
    async update(id: string, entity: DeepPartial<User>): Promise<any> {
        const res = await this.UserRepository.update(id, entity);
        return res;
    }

    // 删除用户信息
    async del(id: string): Promise<any> {
        const res = await this.UserRepository.delete(id);
        console.log(res)
        if (res.affected === 1) {
            return {
                code: 200,
                msg: '删除成功！'
            }
        }
        return {
            code: 400,
            msg: '删除失败！'
        }
    }
}
